﻿using System;
using System.Linq;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASPNETVN.PORTAL.Components.Configuration;
using ASPNETVN.PORTAL.Components.Configuration.Items;
using ASPNETVN.PORTAL.Components.Security;
using ASPNETVN.PORTAL.Components.UI;
using System.Collections.Generic;
using ASPNETVN.PORTAL.Components.Helpers;

namespace ASPNETVN.PORTAL.Modules.TAB.Controls
{
    public partial class AddEditTab : AddEditItemControl
    {
        private void TabDataBind()
        {
            Guid currentTabID = new Guid(Request.QueryString["tid"]);
            Components.Configuration.Items.Portal portal = this.Portal;
            IList<Tab> allTabs = portal.Tabs.Where(x => x.ID != currentTabID).ToList<Tab>();

            foreach (Tab parentTab in allTabs.Where(x => x.ParentID == Guid.Empty).OrderBy(x => x.SortOrder))
            {
                ddlParentTab.Items.Add(new ListItem(parentTab.Name, parentTab.ID.ToString()));
                foreach (Tab childTab in allTabs.Where(x => x.ParentID == parentTab.ID).OrderBy(x => x.SortOrder))
                {
                    ddlParentTab.Items.Add(new ListItem("-- " + childTab.Name, childTab.ID.ToString()));
                }
            }
        }

        protected override void OnInit(EventArgs e)
        {
            // Check if is Administrators role.
            if (!PortalSecurity.IsInRole("1"))
            {
                bool isEditable = PortalSecurity.HasEditAuthorization(this.ModuleID);
                bool isAddable = PortalSecurity.HasAddAuthorization(this.ModuleID);
                bool isDeleteadble = PortalSecurity.HasDeleteAuthorization(this.ModuleID);
                bool isPropertyable = PortalSecurity.HasConfigureAuthorization(this.ModuleID);

                btnAddModule.Enabled = isAddable;
                btnDeleteLeftPane.Enabled = btnDeleteRightPane.Enabled = btnDeleteContentPane.Enabled = isDeleteadble;
                btnSettingLeftPane.Enabled = btnSettingRightPane.Enabled = btnSettingContentPane.Enabled = isEditable;

                btnUpLeftPane.Enabled = btnUpRightPane.Enabled = btnUpContentPane.Enabled = isEditable;
                btnDownLeftPane.Enabled = btnDownRightPane.Enabled = btnDownContentPane.Enabled = isEditable;
                btnRightLeftPane.Enabled = btnRightContentPane.Enabled = isEditable;
                btnLeftRightPane.Enabled = btnLeftContentPane.Enabled = isEditable;

                btnSecurityLeftPane.Enabled = btnSecurityRightPane.Enabled = btnSecurityContentPane.Enabled = isPropertyable;
            }

            ButtonCancel = this.btnCancel;
            ButtonUpdate = this.btnUpdate;

            base.OnInit(e);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
            {
                this.TabDataBind();
                this.MainDataBind();
            }
        }

        private int GetMaxSortOrder(string paneName)
        {
            IList<Module> modules = this.GetModules(paneName);
            if (modules.Count > 0)
            {
                return modules.Max(x => x.SortOrder);
            }
            return 0;
        }

        private void SaveTabData()
        {
            string authorizedRoles = string.Empty;

            foreach (ListItem item in chkRoles.Items)
            {
                if (item.Selected)
                {
                    authorizedRoles = authorizedRoles + item.Value + ";";
                }
            }

            // Lấy dữ liệu từ Current Context.
            Components.Configuration.Items.Portal portal = (Components.Configuration.Items.Portal)Context.Items["Portal"];

            // Lưu thông tin của Tab.
            PortalConfiguration config = new PortalConfiguration();
            Guid tid = new Guid(Request.QueryString["tid"]);
            Guid parentTabID = new Guid(ddlParentTab.SelectedValue);
            config.UpdateTab(portal.ID, tid, parentTabID, txtTabName.Text, Convert.ToInt32(txtSortOrder.Text), authorizedRoles, ddlTheme.SelectedValue, rbLeftPane.Checked, rbRightPane.Checked, chkShowOnMenu.Checked, txtStaticUrl.Text);
        }

        private bool CheckRole(string roleID, string roleString)
        {
            foreach (string r in roleString.Split(';'))
            {
                if (roleID.Trim() == r.Trim())
                {
                    return true;
                }
            }
            return false;
        }


        private void MainDataBind()
        {
            // Obtain Portal from Current Context
            Components.Configuration.Items.Portal portal = this.Portal;
            Guid tid = new Guid(Request.QueryString["tid"]);
            Tab tab = portal.Tabs.First(x => x.ID == tid);

            ddlParentTab.SelectedValue = tab.ParentID.ToString();

            // Static Url.
            txtStaticUrl.Text = tab.StaticUrl;

            // Themes.
            ddlTheme.Items.Clear();
            foreach (string s in Theme.GetThemeList())
            {
                ddlTheme.Items.Add(new ListItem(s, s));
            }

            // Tab information.
            txtTabName.Text = tab.Name;
            ddlTheme.SelectedValue = tab.ThemeName;
            txtSortOrder.Text = tab.SortOrder.ToString();
            rbLeftPane.Checked = tab.ShowLeftPane;
            rbLeftPane_No.Checked = !tab.ShowLeftPane;

            rbRightPane.Checked = tab.ShowRightPane;
            rbRightPane_No.Checked = !tab.ShowRightPane;

            chkShowOnMenu.Checked = tab.ShowOnMenu;

            // Populate checkbox list with all security roles for this portal
            // and "check" the ones already configured for this tab
            DataTable roles = Role.SelectAllByPortalID(Global.PortalID).Tables[0];

            // Clear existing items in checkboxlist
            chkRoles.Items.Clear();
            
            foreach (DataRow row in roles.Rows)
            {
                ListItem item = new ListItem();
                item.Text = (string)row["Name"];
                item.Value = row["ID"].ToString();

                if (this.CheckRole(item.Value, tab.AuthorizedRoles))
                {
                    item.Selected = true;
                }

                // Administrators Role.
                if (item.Value == "1")
                {
                    item.Selected = true;
                    item.Enabled = false;
                }

                chkRoles.Items.Add(item);
            }

            // Populate the "Add Module" Data
            PortalConfiguration config = new PortalConfiguration();
            moduleType.DataSource = config.GetModuleDefinitions(portal.ID);
            moduleType.DataBind();

            // Populate Right Hand Module Data
            lstRightPane.DataSource = this.GetModules("RightPane");
            lstRightPane.DataBind();

            // Populate Content Pane Module Data
            lstContentPane.DataSource = this.GetModules("ContentPane");
            lstContentPane.DataBind();

            // Populate Left Hand Pane Module Data
            lstLeftPane.DataSource = this.GetModules("LeftPane");
            lstLeftPane.DataBind();
        }

        private IList<Module> GetModules(string pane)
        {
            Guid tabID = new Guid(Request.QueryString["tid"]);
            IList<Module> modules = new List<Module>();
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            PortalDataSet.TabRow currentTab = ds.Tab.FindByID(tabID);
            // Get Modules for this Tab based on the Data Relation
            foreach (PortalDataSet.ModuleRow moduleRow in currentTab.GetModuleRows())
            {
                Module module = Module.LoadModuleRow(moduleRow);
                PortalDataSet.ModuleDefinitionRow mdr = ds.ModuleDefinition.FindByID(module.ModuleDefinitionID);

                module.Title = module.Title + " (" + mdr.Name + ")";
                module.TabID = tabID;
                modules.Add(module);
            }

            return modules.Where(x => x.PaneName.ToLower() == pane.ToLower()).OrderBy(x => x.SortOrder).ToList();
        }

        protected void btnSetting_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton button = sender as ImageButton;
            switch (button.CommandArgument.ToLower())
            {
                case "leftpane":
                    if (lstLeftPane.SelectedIndex != -1)
                    {
                        Guid mid = new Guid(lstLeftPane.SelectedItem.Value);
                        string url = HttpUrlBuilder.BuildAdministrationModuleUrl(mid, "StandardSetting");
                        Response.Redirect(url);
                    }
                    break;
                case "contentpane":
                    if (lstContentPane.SelectedIndex != -1)
                    {
                        Guid mid = new Guid(lstContentPane.SelectedItem.Value);
                        string url = HttpUrlBuilder.BuildAdministrationModuleUrl(mid, "StandardSetting");
                        Response.Redirect(url);
                    }
                    break;
                case "rightpane":
                    if (lstRightPane.SelectedIndex != -1)
                    {
                        Guid mid = new Guid(lstRightPane.SelectedItem.Value);
                        string url = HttpUrlBuilder.BuildAdministrationModuleUrl(mid, "StandardSetting");
                        Response.Redirect(url);
                    }
                    break;
            }
        }
       
        protected void btnProperty_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton button = sender as ImageButton;
            switch (button.CommandArgument.ToLower())
            {
                case "leftpane":
                    if (lstLeftPane.SelectedIndex != -1)
                    {
                        Guid mid = new Guid(lstLeftPane.SelectedItem.Value);
                        string url = HttpUrlBuilder.BuildAdministrationModuleUrl(mid, "CustomSetting");
                        Response.Redirect(url);
                    }
                    break;
                case "contentpane":
                    if (lstContentPane.SelectedIndex != -1)
                    {
                        Guid mid = new Guid(lstContentPane.SelectedItem.Value);
                        string url = HttpUrlBuilder.BuildAdministrationModuleUrl(mid, "CustomSetting");
                        Response.Redirect(url);
                    }
                    break;
                case "rightpane":
                    if (lstRightPane.SelectedIndex != -1)
                    {
                        Guid mid = new Guid(lstRightPane.SelectedItem.Value);
                        string url = HttpUrlBuilder.BuildAdministrationModuleUrl(mid, "CustomSetting");
                        Response.Redirect(url);
                    }
                    break;
            }
        }

        protected void btnDeleteModule_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton button = sender as ImageButton;
            IList<Module> modules = this.GetModules(button.CommandArgument);
            switch (button.CommandArgument.ToLower())
            {
                case "leftpane":
                    if (lstLeftPane.SelectedIndex != -1)
                    {
                        Module module = modules.First(x => x.ID == new Guid(lstLeftPane.SelectedItem.Value));
                        PortalConfiguration config = new PortalConfiguration();
                        config.DeleteModule(module.ID);
                        Response.Redirect(Request.RawUrl);
                    }
                    break;
                case "contentpane":
                    if (lstContentPane.SelectedIndex != -1)
                    {
                        Module module = modules.First(x => x.ID == new Guid(lstContentPane.SelectedItem.Value));
                        PortalConfiguration config = new PortalConfiguration();
                        config.DeleteModule(module.ID);
                        Response.Redirect(Request.RawUrl);
                    }
                    break;
                case "rightpane":
                    if (lstRightPane.SelectedIndex != -1)
                    {
                        Module module = modules.First(x => x.ID == new Guid(lstRightPane.SelectedItem.Value));
                        PortalConfiguration config = new PortalConfiguration();
                        config.DeleteModule(module.ID);
                        Response.Redirect(Request.RawUrl);
                    }
                    break;
            }
        }

        private void SwapModuleSortOrder(Module m1, Module m2)
        {
            PortalConfiguration configuration = new PortalConfiguration();
            configuration.SwapModuleSortOrder(m1, m2);
        }

        protected void btnUpDownLeftPane_Click(object sender, ImageClickEventArgs e)
        {
            string commandName = ((ImageButton)sender).CommandName;
            IList<Module> modules = GetModules("LeftPane");

            if (lstLeftPane.SelectedIndex != -1)
            {
                int index = lstLeftPane.SelectedIndex;
                if (commandName == "down")
                {
                    if (index < lstLeftPane.Items.Count - 1)
                    {
                        Module m1 = (Module)modules.First(x => x.ID == new Guid(lstLeftPane.Items[index].Value));
                        Module m2 = (Module)modules.First(x => x.ID == new Guid(lstLeftPane.Items[index + 1].Value));
                        SwapModuleSortOrder(m1, m2);
                        // Redirect to the same page to pick up changes
                        Response.Redirect(Request.RawUrl);
                    }
                }
                else
                {
                    if (index > 0)
                    {
                        Module m1 = (Module)modules.First(x => x.ID == new Guid(lstLeftPane.Items[index].Value));
                        Module m2 = (Module)modules.First(x => x.ID == new Guid(lstLeftPane.Items[index - 1].Value));
                        SwapModuleSortOrder(m1, m2);
                        // Redirect to the same page to pick up changes
                        Response.Redirect(Request.RawUrl);
                    }
                }
            }
        }

        protected void btnUpDownContentPane_Click(object sender, ImageClickEventArgs e)
        {
            string commandName = ((ImageButton)sender).CommandName;
            IList<Module> modules = GetModules("ContentPane");

            if (lstContentPane.SelectedIndex != -1)
            {
                int index = lstContentPane.SelectedIndex;
                if (commandName == "down")
                {
                    if (index < lstContentPane.Items.Count - 1)
                    {
                        Module m1 = (Module)modules.First(x => x.ID == new Guid(lstContentPane.Items[index].Value));
                        Module m2 = (Module)modules.First(x => x.ID == new Guid(lstContentPane.Items[index + 1].Value));
                        SwapModuleSortOrder(m1, m2);
                        // Redirect to the same page to pick up changes
                        Response.Redirect(Request.RawUrl);
                    }
                }
                else
                {
                    if (index > 0)
                    {
                        Module m1 = (Module)modules.First(x => x.ID == new Guid(lstContentPane.Items[index].Value));
                        Module m2 = (Module)modules.First(x => x.ID == new Guid(lstContentPane.Items[index - 1].Value));
                        SwapModuleSortOrder(m1, m2);
                        // Redirect to the same page to pick up changes
                        Response.Redirect(Request.RawUrl);
                    }
                }
            }
        }

        protected void btnUpDownRightPane_Click(object sender, ImageClickEventArgs e)
        {
            string commandName = ((ImageButton)sender).CommandName;
            IList<Module> modules = GetModules("RightPane");

            if (lstRightPane.SelectedIndex != -1)
            {
                int index = lstRightPane.SelectedIndex;
                if (commandName == "down")
                {
                    if (index < lstRightPane.Items.Count - 1)
                    {
                        Module m1 = (Module)modules.First(x => x.ID == new Guid(lstRightPane.Items[index].Value));
                        Module m2 = (Module)modules.First(x => x.ID == new Guid(lstRightPane.Items[index + 1].Value));
                        SwapModuleSortOrder(m1, m2);
                        // Redirect to the same page to pick up changes
                        Response.Redirect(Request.RawUrl);
                    }
                }
                else
                {
                    if (index > 0)
                    {
                        Module m1 = (Module)modules.First(x => x.ID == new Guid(lstRightPane.Items[index].Value));
                        Module m2 = (Module)modules.First(x => x.ID == new Guid(lstRightPane.Items[index - 1].Value));
                        SwapModuleSortOrder(m1, m2);
                        // Redirect to the same page to pick up changes
                        Response.Redirect(Request.RawUrl);
                    }
                }
            }
        }

        protected void btnRightLeftPane_Click(object sender, ImageClickEventArgs e)
        {
            if (lstLeftPane.SelectedIndex != -1)
            {
                // get source arraylist
                IList<Module> sourceList = GetModules("LeftPane");

                // get a reference to the module to move
                // and assign a high order number to send it to the end of the target list
                Module m = (Module)sourceList[lstLeftPane.SelectedIndex];

                // add it to the database
                PortalConfiguration config = new PortalConfiguration();
                config.UpdateModuleSortOrder(m.ID, 998, "ContentPane");

                // delete it from the source list
                sourceList.RemoveAt(lstLeftPane.SelectedIndex);

                // Obtain portalId from Current Context
                Components.Configuration.Items.Portal portal = (Components.Configuration.Items.Portal)Context.Items["Portal"];

                // reload the portal from the database
                HttpContext.Current.Items["Portal"] = new Components.Configuration.Items.Portal(TabID);

                // reorder the modules in the source pane
                sourceList = GetModules("LeftPane");

                // resave the order
                foreach (Module item in sourceList)
                {
                    config.UpdateModuleSortOrder(item.ID, item.SortOrder, "LeftPane");
                }

                // reorder the modules in the target pane
                IList<Module> targetList = GetModules("ContentPane");

                // resave the order
                foreach (Module item in targetList)
                {
                    config.UpdateModuleSortOrder(item.ID, item.SortOrder, "ContentPane");
                }

                // Redirect to the same page to pick up changes
                Response.Redirect(Request.RawUrl);
            }
        }

        protected void btnLeftRightPane_Click(object sender, ImageClickEventArgs e)
        {
            if (lstRightPane.SelectedIndex != -1)
            {
                // get source arraylist
                IList<Module> sourceList = GetModules("RightPane");

                // get a reference to the module to move
                // and assign a high order number to send it to the end of the target list
                Module m = (Module)sourceList[lstRightPane.SelectedIndex];

                // add it to the database
                PortalConfiguration config = new PortalConfiguration();
                config.UpdateModuleSortOrder(m.ID, 998, "ContentPane");

                // delete it from the source list
                sourceList.RemoveAt(lstRightPane.SelectedIndex);

                // Obtain portalId from Current Context
                Components.Configuration.Items.Portal portal = (Components.Configuration.Items.Portal)Context.Items["Portal"];

                // reload the portal from the database
                HttpContext.Current.Items["Portal"] = new Components.Configuration.Items.Portal(TabID);

                // reorder the modules in the source pane
                sourceList = GetModules("RightPane");

                // resave the order
                foreach (Module item in sourceList)
                {
                    config.UpdateModuleSortOrder(item.ID, item.SortOrder, "RightPane");
                }

                // reorder the modules in the target pane
                IList<Module> targetList = GetModules("ContentPane");

                // resave the order
                foreach (Module item in targetList)
                {
                    config.UpdateModuleSortOrder(item.ID, item.SortOrder, "ContentPane");
                }

                // Redirect to the same page to pick up changes
                Response.Redirect(Request.RawUrl);
            }
        }

        protected void btnLeftContentPane_Click(object sender, ImageClickEventArgs e)
        {
            if (lstContentPane.SelectedIndex != -1)
            {
                // get source arraylist
                IList<Module> sourceList = GetModules("ContentPane");

                // get a reference to the module to move
                // and assign a high order number to send it to the end of the target list
                Module m = (Module)sourceList[lstContentPane.SelectedIndex];

                // add it to the database
                PortalConfiguration config = new PortalConfiguration();
                config.UpdateModuleSortOrder(m.ID, 998, "LeftPane");

                // delete it from the source list
                sourceList.RemoveAt(lstContentPane.SelectedIndex);

                // Obtain portalId from Current Context
                Components.Configuration.Items.Portal portal = (Components.Configuration.Items.Portal)Context.Items["Portal"];

                // reload the portal from the database
                HttpContext.Current.Items["Portal"] = new Components.Configuration.Items.Portal(TabID);

                // reorder the modules in the source pane
                sourceList = GetModules("ContentPane");

                // resave the order
                foreach (Module item in sourceList)
                {
                    config.UpdateModuleSortOrder(item.ID, item.SortOrder, "ContentPane");
                }

                // reorder the modules in the target pane
                IList<Module> targetList = GetModules("LeftPane");

                // resave the order
                foreach (Module item in targetList)
                {
                    config.UpdateModuleSortOrder(item.ID, item.SortOrder, "LeftPane");
                }

                // Redirect to the same page to pick up changes
                Response.Redirect(Request.RawUrl);
            }
        }

        protected void btnRightContentPane_Click(object sender, ImageClickEventArgs e)
        {
            if (lstContentPane.SelectedIndex != -1)
            {
                // get source arraylist
                IList<Module> sourceList = GetModules("ContentPane");

                // get a reference to the module to move
                // and assign a high order number to send it to the end of the target list
                Module m = (Module)sourceList[lstContentPane.SelectedIndex];

                // add it to the database
                PortalConfiguration config = new PortalConfiguration();
                config.UpdateModuleSortOrder(m.ID, 998, "RightPane");

                // delete it from the source list
                sourceList.RemoveAt(lstContentPane.SelectedIndex);

                // Obtain portalId from Current Context
                Components.Configuration.Items.Portal portal = (Components.Configuration.Items.Portal)Context.Items["Portal"];

                // reload the portal from the database
                HttpContext.Current.Items["Portal"] = new Components.Configuration.Items.Portal(TabID);

                // reorder the modules in the source pane
                sourceList = GetModules("ContentPane");

                // resave the order
                foreach (Module item in sourceList)
                {
                    config.UpdateModuleSortOrder(item.ID, item.SortOrder, "ContentPane");
                }

                // reorder the modules in the target pane
                IList<Module> targetList = GetModules("RightPane");

                // resave the order
                foreach (Module item in targetList)
                {
                    config.UpdateModuleSortOrder(item.ID, item.SortOrder, "RightPane");
                }

                // Redirect to the same page to pick up changes
                Response.Redirect(Request.RawUrl);
            }
        }

        protected void btnSecurity_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton button = sender as ImageButton;
            switch (button.CommandArgument.ToLower())
            { 
                case "leftpane":
                    if (lstLeftPane.SelectedIndex != -1)
                    {
                        IList<Module> modules = this.GetModules(button.CommandArgument);
                        Module module = modules.First(x => x.ID == new Guid(lstLeftPane.SelectedItem.Value));
                        string url = HttpUrlBuilder.BuildAdministrationModuleUrl(module.ID, "Permission");
                        Response.Redirect(url);
                    }
                    break;
                case "contentpane":
                    if (lstContentPane.SelectedIndex != -1)
                    {
                        IList<Module> modules = this.GetModules(button.CommandArgument);
                        Module module = modules.First(x => x.ID == new Guid(lstContentPane.SelectedItem.Value));
                        string url = HttpUrlBuilder.BuildAdministrationModuleUrl(module.ID, "Permission");
                        Response.Redirect(url);
                    }
                    break;
                case "rightpane":
                    if (lstRightPane.SelectedIndex != -1)
                    {
                        IList<Module> modules = this.GetModules(button.CommandArgument);
                        Module module = modules.First(x => x.ID == new Guid(lstRightPane.SelectedItem.Value));
                        string url = HttpUrlBuilder.BuildAdministrationModuleUrl(module.ID, "Permission");
                        Response.Redirect(url);
                    }
                    break;
            }
        }

        protected override void OnUpdate(EventArgs e)
        {
            base.OnUpdate(e);
            this.SaveTabData();

            // Refresh page.
            Response.Redirect(Request.RawUrl);
        }

        protected void btnAddModule_Click(object sender, EventArgs e)
        {
            string paneName = ddlPane.SelectedValue;
            // Xem lại:
            // Thêm mới 1 module vào cuối danh sách.
            Module m = new Module();
            m.Title = moduleTitle.Text;
            m.ModuleDefinitionID = new Guid(moduleType.SelectedItem.Value);
            m.SortOrder = this.GetMaxSortOrder(paneName) + 1;

            // Lưu vào tập tin xml.
            PortalConfiguration config = new PortalConfiguration();
            Guid tid = new Guid(Request.QueryString["tid"]);
            m.ID = config.AddModule(tid, m.SortOrder, ddlPane.SelectedValue, false, m.Title, m.ModuleDefinitionID, 0, "-1;", "1;", "1;", "1;", "1;", "1;", "1;", "1;");

            // Refresh page.
            Response.Redirect(Request.RawUrl);
        }
    }
}